<template>
  <a-cascader :options="options"
  v-model="defop"
  :load-data="loadData" placeholder="请选择" change-on-select
    @change="onChange" />
</template>
<script>
  import {
    ajaxGetDictItems,
    getDictItemsFromCache
  } from '@/api/api'
  export default {
    data() {
      return {
        defop:[],
        options: [ ],
      };
    },
    props:{
      num:{
        type:Number,
        default:3 //显示到那个层级 1仅装置  2装置+区域  3装置+区域+设备
      }
    },
    created() {
      this.initDictData("LOCATIONA,name,code",1);
    },
    methods: {
      initDictData(dictCode,level) {
        if (getDictItemsFromCache(dictCode)) {
          this.options = getDictItemsFromCache(dictCode).map(s => {
            return {
              ...s,
              isLeaf: false,level
            }
          });
          return
        }
        ajaxGetDictItems(dictCode, null).then((res) => {
          if (res.success) {
            this.options = res.result.map(s => {
              return {
                ...s,
                isLeaf: this.num==1 ,level
              }
            });
          }
        })
      },
      onclose(){
        this.defop = [];
      },
      onChange(value) {
        this.$emit("input",value)
        this.$emit("change",value)
      },
      loadData(selectedOptions) {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        // load options lazily
        console.log(targetOption);
        if(targetOption.level == 1){
          ajaxGetDictItems(`locationb,name,code,locationa='${targetOption.value}'`, null).then((res) => {
            if (res.success) {
              targetOption.loading = false;
              targetOption.children = res.result.map(s => {
                return {
                  ...s,
                  isLeaf: this.num==2,level:targetOption.level+1
                }
              });
              this.options = [...this.options];
            }
          })
        }
        if(targetOption.level == 2){
          ajaxGetDictItems(`locationc,name,code,locationb='${targetOption.value}'`, null).then((res) => {
            if (res.success) {
              targetOption.loading = false;
              targetOption.children = res.result.map(s => {
                return {
                  ...s,
                  isLeaf: this.num==3,level:targetOption.level+1
                }
              });
              this.options = [...this.options];
            }
          })
        }
      },
    },
  };
</script>